<template>
  <!-- 上传视频 -->
  <v-card>
    <VCard>
      <VRow>
        <VCol cols="6">
          <VCard border="dashed" min-height="'300px'" class="ma-4" :variant="'outlined'"
                 style="text-align: center;">
            <VList density="compact" style="margin: 0 auto;">
              <VListItem>
                <VIcon color="blue" :size="50">mdi-upload</VIcon>
              </VListItem>
              <VListItem>
                <VCardSubtitle>拖到此处可上传</VCardSubtitle>
              </VListItem>
              <VListItem>
                <VBtn color="primary" @click="videoFileRef.click()">上传视频</VBtn>
              </VListItem>
              <VListItem>
                <v-chip class="ma-2 font-weight-bold" color="green" label>
                  <v-icon start :icon="'mdi-file-cloud-outline'"></v-icon>
                  审核队列: {{ queueState }}
                </v-chip>
              </VListItem>
            </VList>
            <div style="display: none;">
              <form>
                <input v-on:change="uploadVideo" ref="videoFileRef" type="file" accept="video/*" />
              </form>
            </div>
          </VCard>
        </VCol>
        <VCol cols="6">
          <v-list :density="'compact'" lines="three" class="mt-2">
            <VListItemTitle>
              <VIcon>mdi-menu-down</VIcon>用户须知
            </VListItemTitle>
            <v-list-item v-for="(item, i) in items" :key="i" link>
              <template v-slot:prepend>
                <v-avatar class="me-4 mt-2" rounded="0">
                  <v-img :src="item.image" cover></v-img>
                </v-avatar>
              </template>

              <v-list-item-title class="text-uppercase font-weight-regular text-caption"
                                 v-text="item.category"></v-list-item-title>
              <div v-text="item.title"></div>
            </v-list-item>
          </v-list>
        </VCol>
      </VRow>
    </VCard>
    <VCard v-if="uploadList.length > 0">
      <v-item-group mandatory>
        <VCardTitle>基本信息</VCardTitle>
        <VDivider></VDivider>
        <v-container>
          <v-row>
            <v-col v-for="(uploadItem, index) in uploadList" :key="index" cols="12" md="3">
              <v-item v-slot="{ isSelected, toggle }">
                <v-card :color="isSelected ? 'primary' : 'white'" dark height="100"
                        @click="() => { toggle(); currentVideoIndex = index }">
                  <v-scroll-y-transition>
                    <div>
                      <v-card-title>{{ uploadItem.title }}</v-card-title>
                      <VCardText class="pb-0">
                        <v-progress-linear color="orange" striped :model-value="uploadItem.progress"
                                           height="25">
                          <strong>{{ Math.ceil(uploadItem.progress) }}%</strong>
                        </v-progress-linear>
                      </VCardText>
                    </div>
                  </v-scroll-y-transition>
                </v-card>
              </v-item>
            </v-col>
          </v-row>
        </v-container>
      </v-item-group>
      <v-card-text v-if="currentVideo">
        <VideoEdit :current-video="currentVideo" :clear="clearUp" :save="pushVideo" />
      </v-card-text>
    </VCard>
    <v-snackbar v-model="snackbar.show" :color="snackbar.color">
      {{ snackbar.text }}
      <template v-slot:actions>
        <v-btn color="blue" variant="text" @click="snackbar.show = false">
          了解
        </v-btn>
      </template>
    </v-snackbar>
  </v-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 用于显示提示信息的Snackbar对象
const snackbar = ref({
  show: false,
  text: "",
  color: "success"
});

// 引用视频文件的input元素
const videoFileRef = ref(null);

// 用于存储上传视频的列表
const uploadList = ref([]);

// 存储审核队列的状态信息
const queueState = ref('空闲中');

// 当前正在上传的视频索引
const currentVideoIndex = ref(null);

// 存储当前用户信息
const currentUser = ref(null);

// 获取当前用户信息函数
const fetchCurrentUser = async () => {
  try {
    const response = await axios.get('/api/user/current');
    currentUser.value = response.data;
  } catch (error) {
    console.error('获取当前用户信息失败:', error);
  }
};

// 上传视频函数
const uploadVideo = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    // 确保用户信息已获取
    if (!currentUser.value) {
      await fetchCurrentUser();
    }

    // 第一步：获取OSS的预签名URL
    const response = await axios.get(`/api/oss/generatePresignedUrl`, {
      params: { objectName: file.name }
    });
    const presignedUrl = response.data;

    // 第二步：使用预签名URL上传文件到OSS
    const uploadResponse = await axios.put(presignedUrl, file, {
      headers: { 'Content-Type': file.type },
      onUploadProgress: (progressEvent) => {
        const progress = (progressEvent.loaded / progressEvent.total) * 100;
        if (uploadList.value.length > 0) {
          uploadList.value[0].progress = progress;
        } else {
          uploadList.value.push({ title: file.name, progress });
        }
      }
    });

    if (uploadResponse.status === 200) {
      snackbar.value.text = "文件上传成功!";
      snackbar.value.color = "success";
      snackbar.value.show = true;

      // 提交视频基本信息到后端
      const videoInfo = {
        title: file.name,
        url: presignedUrl.split('?')[0], // OSS 文件URL
        description: '默认描述', // 可以根据需要自定义
        userId: currentUser.value.id, // 从当前用户中获取用户ID
        typeId: 1, // 这里假设类别ID为1，根据实际情况传递
        open: 0, // 公开状态，0表示公开
        cover: '', // 可以根据实际需求传递封面
        auditStatus: 0, // 初始审核状态
        auditQueueStatus: 0, // 初始审核队列状态
        startCount: 0, // 初始点赞数
        shareCount: 0, // 初始分享数
        historyCount: 0, // 初始播放历史数
        favoritesCount: 0, // 初始收藏数
        labelNames: '', // 视频标签
        videoType: '', // 视频类型
        duration: '' // 视频时长
      };

      await axios.post('/api/video/save', videoInfo);
      snackbar.value.text = "视频信息保存成功!";
    } else {
      snackbar.value.text = "文件上传失败!";
      snackbar.value.color = "error";
      snackbar.value.show = true;
    }
  } catch (error) {
    snackbar.value.text = `上传失败: ${error.message}`;
    snackbar.value.color = "error";
    snackbar.value.show = true;
  }
};

// 在组件初始化时获取当前用户信息
onMounted(fetchCurrentUser);

// items数组存储用户须知信息，用于在页面上展示
const items = ref([
  {
    image: 'https://cdn.vuetifyjs.com/docs/images/chips/globe.png',
    title: '视频格式支持：mp4、avi、aav、cawd',
    category: '视频',
  },
  {
    image: 'https://cdn.vuetifyjs.com/docs/images/chips/cpu.png',
    title: '发布视频后会进行视频审核。(七牛云服务自动审核)',
    category: '审核',
  },
  {
    image: 'https://cdn.vuetifyjs.com/docs/images/chips/rocket.png',
    title: '您的视频将会被存储在七牛云的对象存储服务中。',
    category: '存储',
  }
]);
</script>


<!--
/*const currentVideoIndex = ref(null)
const videoFileRef = ref()
const uploadList = ref([])
const queueState = ref("快速")
const currentVideo = computed(() => currentVideoIndex.value > -1 ? uploadList.value[currentVideoIndex.value] : null)
onMounted(() => {
getQueueState()
})
const getQueueState = () => {
apiGetAuditQueueState().then(({ data }) => {
if (!data.state) {
return
}
queueState.value = data.message
})
}
const clearUp = () => {
if (currentVideo.value.status < 1) {
currentVideo.value.subscription.unsubscribe()
}
uploadList.value.splice(currentVideoIndex.value, 1);
}
const pushVideo = (data) => {
snackbar.value = {
text: data.message,
show: true
}
if(data.state) {
clearUp();
getQueueState()
}

}
const uploadVideo = async () => {
if(!videoFileRef.value.files[0]) return;
let curFile = videoFileRef.value.files[0]
const curUploadInfo = {
progress: 0,
status: 0,
msg: "",
result: "",
title: curFile.name,
description: "",
url: "",
cover: "",
file: curFile,
labelNames: []
}
uploadList.value.push(curUploadInfo)
if(uploadList.value.length==1) {
currentVideoIndex.value = 0
}
curUploadInfo.subscription = await apiUploadFile(curFile, {
next: (e) => {
curUploadInfo.progress = e.total.percent
uploadList.value = Object.assign([], uploadList.value)
}, error: (e) => {
curUploadInfo.status = -1
curUploadInfo.msg = "上传失败：" + e
uploadList.value = Object.assign([], uploadList.value)
},
complete: (e,fileId) => {
if(!fileId.state) {
snackbar.value = {
text: fileId.message,
show: true
}
return;
}
curUploadInfo.result = e
curUploadInfo.status = 1
curUploadInfo.url = fileId.data
curUploadInfo.cover = null
uploadList.value = Object.assign([], uploadList.value)
}
})
videoFileRef.value.value = ""
}*/-->
